package com.itheima.leyou.interceptor;

import com.itheima.leyou.common.exception.LyException;
import com.itheima.leyou.common.utils.CookieUtils;
import com.itheima.leyou.constants.JwtConstants;
import com.itheima.leyou.dto.Payload;
import com.itheima.leyou.dto.UserDetail;
import com.itheima.leyou.utils.JwtUtils;
import com.itheima.leyou.utils.UserContext;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private JwtUtils jwtUtils;
    public LoginInterceptor(JwtUtils jwtUtils){
        this.jwtUtils=jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            //获取cookie中的token信息
            String token = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
            //解析token
            Payload jwt = jwtUtils.parseJwt(token);
            //获取用户信息
            UserDetail userDetail = jwt.getUserDetail();
            log.info("用户{}" + userDetail.getUsername()+"正在访问当前页面");
            //将用户信息保存在当前先成中
            UserContext.setUser(userDetail);
            return true;
        } catch (JwtException e) {
            throw new LyException(401, "JWT无效或过期!", e);
        }catch (IllegalArgumentException e){
            throw new LyException(401, "用户未登录!", e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
            //删除当前线程中的用户信息
            UserContext.removeUser();

    }
}
